#pragma once
#include "TrTypes.h"
#include "TrSession.h"
#include "TrSingleton.h"
#include <string>
#include <functional>
#include <QMap>
#include <memory>
#include <vector>

namespace Market {

// Bar数据回调函数类型
using BarCallback = std::function<void(const std::string&, const WTSBarStruct&)>;

// 单个合约的单个周期Bar生成器
class PeriodGenerator {
public:
    PeriodGenerator(const QString& symbol, TrPeriod period, const QString& sessionName)
        : m_symbol(symbol)
        , m_period(period)
        , m_sessionName(sessionName) {
        // 获取该周期的时间点列表
        m_timePoints = SESSION->Get(m_sessionName, m_period);
    }

    void setCallback(BarCallback callback) { m_callback = callback; }
    void onTick(const WTSTickStruct& tick);

private:
    QString m_symbol;
    TrPeriod m_period;
    QString m_sessionName;
    QVector<QString> m_timePoints;
    BarCallback m_callback;
    WTSBarStruct m_currentBar;
    bool m_hasBar{false};
};

class BarGenerator : public TrSingleton<BarGenerator> 
{
    friend class TrSingleton<BarGenerator>;
public:
    // 为合约添加指定周期的Bar生成器
    void addGenerator(const QString& symbol, TrPeriod period, 
                     const QString& sessionName, BarCallback callback);
    // 处理Tick数据
    void onTick(const WTSTickStruct& tick);
private:
    // 存储每个合约的不同周期Bar生成器
    // key: symbol.period (如 "SHFE.au2306.M1")
    QMap<QString, std::shared_ptr<PeriodGenerator>> m_Generators;
};

#define BAR_GENERATOR Market::BarGenerator::instance()

} // namespace Market